"""
Bundles are groups of widgets
Written By: Daniel Ortiz
"""
class Bundle(object):
    def __init__(self, cls, p):
        self.cls = cls
        self.p = p
        self.Variables()
        
    def Variables(self):
        """Iniitate class wide variables"""
        self.bundle = []
        self.callback = []
        self.bundle_pos = []
        self.pos = 0
        self.previous_obj = None
        
    def Add(self, obj, callback):
        """Add an object to the bundle"""
        if isinstance(obj, self.cls):
            self.bundle.append(obj)
            self.callback.append(callback)
            
    def CurrentObject(self, pos):
        """Return the current object that corresponds to a certain position"""
        for key, cpos in enumerate(self.bundle_pos):
            if pos >= cpos[0] and pos < cpos[1]:
                return self.bundle[key]
        return None
    
    def CurrentString(self):
        """Return the current string of the bundle"""
        buf = ''
        pos = 0
        self.bundle_pos = []
        for c in self.callback:
            str = c()
            l = len(str)
            buf = buf + str
            self.bundle_pos.append((pos, pos + l))
            pos = pos + l 
        return buf
    
    def CallFunction(self, pos, func, *args, **kwargs):
        """Call object at certain position"""
        obj = self.CurrentObject(pos)
        obj.SetFocus()
        if obj:
            if isinstance(func, basestring):
                attr = getattr(obj, func)
            else:
                attr = getattr(obj, str(func))
            if kwargs.has_key('in_context'):
                if kwargs['in_context']:
                    args = self.ConvertPositionToContext(obj, *args)
                print args
                attr(*args)
            else:
                attr(*args)
        self.previous_obj = obj

    def ConvertPositionToContext(self, obj, *args):
        """Converts the positions in args to the index of the widget"""
        arg = []
        pos = self.bundle_pos[self.bundle.index(obj)][0]
        for a in args:
            if isinstance(a, int):
                arg.append(a - pos)
            else:
                arg.append(a)
        return arg
    
    def LogFocus(self, obj):
        """Keep a log of the text ctrl that has focus"""
        self.bundle_focus = obj
        
    def GetCurrentLocation(self):
        """Get the current location from the user focus"""
        return self.bundle_focus.GetInsertionPoint()
            
    
    